#pragma once

#include<vector>
#include<iostream>

using namespace std;

namespace bit
{
	template<class k>
	struct Hashfunc
	{
		size_t operator()(const k& _kv)
		{

			return (size_t)_kv;
		}
	};

	template<>
	struct Hashfunc<string>
	{
		size_t operator()(const string& _kv)
		{
			size_t a = 0;
			for (auto e : _kv)
			{
				a += e;
				a *= 31;
			}
			return a;
		}
	};

	template<class k, class v>
	struct HashNode
	{
		pair<k, v> _kv;
		HashNode<k, v>* _next;



		HashNode(const pair<k, v>& kv)
			: _kv(kv)
			,_next(nullptr)
		{ }
	};

	template<class k, class v, class Hash = Hashfunc<k>>
	class HashTable
	{
		typedef HashNode<k, v> Node;
	public:

		HashTable()
		{
			_tables.resize(10, nullptr);
		}

		~HashTable()
		{
			for (size_t i = 0; i < _tables.size(); i++)
			{
				while (_tables[i])
				{
					Node* root = _tables[i]->_next;
					delete _tables[i];
					_tables[i] = root;
				}
				_tables[i] = nullptr;
			}
		}

		bool insert(const pair<k, v>& kv)
		{
			Hash hot;
			if (_n == _tables.size())
			{
				vector<Node*> _newtables(_tables.size() * 2, nullptr);
				for (size_t i = 0; i < _tables.size(); i++)
				{
					while(_tables[i])
					{
						Node* root = _tables[i]->_next;
						int hashi = hot(_tables[i]->_kv.first) % (_tables.size()*2);
						_tables[i]->_next = _newtables[hashi];
						_newtables[hashi] = _tables[i];
						_tables[i] = root;
					}
				}
				_tables.swap(_newtables);
			}
			int hashi = hot(kv.first) % _tables.size();
			Node* root = _tables[hashi];
			_tables[hashi] = new Node(kv);
			_tables[hashi]->_next = root;
			_n++;
			return true;
		}

		Node* find(const k& key)
		{
			Hash hot;
			int hashi = hot(key) % _tables.size();
			Node* root = _tables[hashi];
			while (root)
			{
				if (root->_kv.first == key)
				{
					return root;
				}
				root = root->_next;
			}
			return nullptr;
		}

		bool erase(const k& key)
		{
			Hash hot;
			int hashi = hot(key) % _tables.size();
			Node* root = _tables[hashi];
			Node* prev = nullptr;
			while (root)
			{
				if (root->_kv.first == key)
				{
					if (prev == nullptr)
					{
						_tables[hashi] = root->_next;
					}
					else
					{
						prev->_next = root->_next;
					}
					delete root;
					_n--;
					return true;
				}
				prev = root;
				root = root->_next;
			}
			return false;
		}


	private:
		vector<Node*> _tables;
		size_t _n = 0;
	};
}
